const fs = require('fs')
const path = require('path')
const { src, dest, parallel, watch, series, task } = require('gulp')
const clean = require('gulp-clean')
const less = require('gulp-less')
const autoprefixer = require('gulp-autoprefixer')
const rename = require("gulp-rename")
const cleanCSS = require('gulp-clean-css')
const htmlmin = require('gulp-htmlmin')
const ts = require("gulp-typescript")
const babel = require('gulp-babel')
const uglify = require('gulp-uglify')
const imagemin = require('gulp-imagemin')
const tsProject = ts.createProject("tsconfig.json")
const { readFile } = require('./build/util')
let ignorePages = []

const buildIgnoreJsonPath = path.resolve(__dirname, './temp/buildIgnore.json')
if (fs.existsSync(buildIgnoreJsonPath)) {
	ignorePages = Object.assign(ignorePages, readFile(buildIgnoreJsonPath, true))
}

function cleanDist() {
	return src('./dist/*', {
		ignore: [
			'./dist/app.json',
			'./dist/sitemap.json',
			'./dist/project.config.json',
			'./dist/env.config.js',
		]
	})
		.pipe(clean({ force: true }))
}

function buildLess() {
	return src(['./src/**/*.less'], {
		ignore: [...ignorePages]
	})
		.pipe(less())
		.pipe(autoprefixer({}))
		.pipe(cleanCSS({}))
		.pipe(rename({
			extname: ".wxss"
		}))
		.pipe(dest('dist'))
}

function buildTs() {
	// return tsProject.src()
	return src(['./src/**/*.ts', './typings/**/*.ts'], {
		ignore: ["./node_modules/*",
			"./dist/*",
			"src/env.config.ts",
			...ignorePages
		]
	})
		.pipe(tsProject())
		.pipe(uglify())
		.pipe(dest("dist"))
}

function buildWxml() {
	return src(['./src/**/*.wxml'], {
		ignore: [...ignorePages]
	})
		.pipe(htmlmin({
			removeComments: true,//清除HTML注释
			collapseWhitespace: true,//压缩HTML
			minifyJS: true,//压缩页面JS
			minifyCSS: true//压缩页面CSS
		}))
		.pipe(dest('dist'))
}

function buildJson() {
	return src(['./src/**/*.json'], {
		ignore: [...ignorePages]
	})
		.pipe(dest('dist'))
}

function buildJs() {
	return src(['./src/**/*.js'], {
		ignore: [...ignorePages]
	})
		.pipe(babel())
		.pipe(uglify())
		.pipe(dest('dist'))
}

function buildImg() {
	return src(['./src/**/*.png', './src/**/*.jpg', './src/**/*.svg'], {
		ignore: [...ignorePages]
	})
		.pipe(imagemin())
		.pipe(dest('dist'))
}


const processAll = parallel(buildLess, buildWxml, buildTs, buildJs, buildJson, buildImg)

async function developmentWatch(cb) {
	watch(['./src/**/*.less'], series(buildLess))
	watch(['./src/**/*.wxml'], series(buildWxml))
	watch(['./src/**/*.ts', './typings/**/*.ts'], series(buildTs))
	watch(['./src/**/*.js'], series(buildJs))
	watch(['./src/**/*.json'], series(buildJson))
	watch(['./src/**/*.png', './src/**/*.jpg', './src/**/*.svg'], series(buildImg))
}

exports.clean = series(cleanDist)
exports.watch = series(cleanDist, processAll, developmentWatch)
exports.default = series(cleanDist, processAll)